import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import '../styles/Login.css';

const Login = () => {
  const navigate = useNavigate();
  const { login, isAuthenticated, error, clearError } = useAuth();
  const [loginError, setLoginError] = useState('');

  // 如果已经登录则重定向到仪表盘
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/dashboard');
    }
  }, [isAuthenticated, navigate]);

  // 处理表单提交
  const handleSubmit = async (values, { setSubmitting }) => {
    try {
      await login(values.username, values.password);
      navigate('/dashboard');
    } catch (err) {
      setLoginError(err.response?.data?.message || '登录失败，请检查用户名和密码');
    } finally {
      setSubmitting(false);
    }
  };

  // 登录表单验证规则
  const validationSchema = Yup.object({
    username: Yup.string().required('请输入用户名'),
    password: Yup.string().required('请输入密码')
  });

  // 清除错误信息
  useEffect(() => {
    return () => clearError();
  }, [clearError]);

  return (
    <div className="login-container">
      <div className="login-form-container">
        <div className="login-header">
          <h1>情报采集监控系统</h1>
          <p>登录您的账户</p>
        </div>

        {(loginError || error) && (
          <div className="login-error">
            {loginError || error}
          </div>
        )}

        <Formik
          initialValues={{ username: '', password: '' }}
          validationSchema={validationSchema}
          onSubmit={handleSubmit}
        >
          {({ isSubmitting }) => (
            <Form className="login-form">
              <div className="form-group">
                <label htmlFor="username">用户名</label>
                <Field
                  type="text"
                  id="username"
                  name="username"
                  placeholder="请输入用户名或邮箱"
                />
                <ErrorMessage name="username" component="div" className="error-message" />
              </div>

              <div className="form-group">
                <label htmlFor="password">密码</label>
                <Field
                  type="password"
                  id="password"
                  name="password"
                  placeholder="请输入密码"
                />
                <ErrorMessage name="password" component="div" className="error-message" />
              </div>

              <button
                type="submit"
                className="login-button"
                disabled={isSubmitting}
              >
                {isSubmitting ? '登录中...' : '登录'}
              </button>
            </Form>
          )}
        </Formik>
      </div>
    </div>
  );
};

export default Login; 